import { ReactNode, useState } from 'react';

import { transformArrayIntoObject } from '@/shared/lib/transformArrayIntoObject';
import { Button, ButtonVariants } from '@/shared/ui/Button';
import cn from 'classnames';

import cs from './List.module.scss';

export const List = ({
  list,
  isExtensible,
  className,
}: {
  className?: string;
  list?: ReactNode[];
  isExtensible?: number;
}) => {
  const [isExtended, setIsExtended] = useState(false);
  const fixedList = transformArrayIntoObject(
    (isExtensible && !isExtended ? list?.slice(0, isExtensible) : list) as ReactNode[],
  );
  const canShowAll = isExtensible !== undefined && (list?.length || 0) > isExtensible && !isExtended;
  return (
    <div className={cn(cs.list, className)}>
      {fixedList?.map(({ title: item, id: index }) => (
        <div className={cs.item} key={index}>
          {item}
        </div>
      ))}
      {canShowAll && (
        <div className={cs.extend_container}>
          <Button
            className={cs.extend}
            data-testid="button-show_all"
            onClick={() => setIsExtended(true)}
            type="button"
            variant={ButtonVariants.Link}
          >
            <span>Показать все</span>
          </Button>
        </div>
      )}
    </div>
  );
};
